﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;

namespace Xman.Dapper
{
    public class SqlContext : DapperContext
    {
        public SqlContext(IOptions<DapperContextOptions> options) : base(options) { }


        public async Task BlukInsertAsync<T>(IEnumerable<T> entityList)
        {
            await using var connection = await OpenConnectionAsync() as SqlConnection;
            using var bulkCopy = new SqlBulkCopy(connection);
            bulkCopy.BatchSize = entityList.Count();
            bulkCopy.DestinationTableName = typeof(T).Name;
            var table = new DataTable();
            var props = typeof(T).GetProperties();
            foreach (var propertyInfo in props)
            {
                bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
                table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
            }
            var values = new object[props.Length];
            foreach (var item in entityList)
            {
                for (var i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                table.Rows.Add(values);
            }
            await bulkCopy.WriteToServerAsync(table);
        }

    }
}
